package org.langqiao.io.file;

import javax.swing.*; 
import javax.swing.event.*; 
import javax.swing.tree.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.File; 
import java.util.*; 
public class FileManagerJFrame extends JFrame implements TreeExpansionListener,TreeSelectionListener,ActionListener{ 

//定义常量 
    private final JTree tree ;  
    private final JPanel sfile; 
    private final JSplitPane split; 
    private final JPanel statusBar; 
    private final JLabel statusLabel; 


//构造函数 
    public FileManagerJFrame() { 
    Dimension dimension = getToolkit().getScreenSize(); 
    this.setBounds(dimension.width/4,dimension.height/4,640,480); 
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭窗口
    this.setVisible(true);
   

//分割窗口 
//水平分割，左scrollPane内放tree，右放pSub用于显示文件 
    tree=new JTree(createTreeModel());
    sfile=new JPanel(new GridLayout(100,0));
    split=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,new JScrollPane(tree),new JScrollPane(sfile)); 
    split.setLastDividerLocation(200); //将分隔条最后的位置设置为从窗口框架左侧到分隔条左侧，200像素
    this.getContentPane().add(split); //在窗口框架中添加分隔面板


    sfile.setBackground(Color.white);//背景色为白  

//给树添加展开监听器 
    tree.addTreeExpansionListener(this); 
    tree.addTreeSelectionListener(this); 

    //设置树的外形 
    try 
    { 
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
        SwingUtilities.updateComponentTreeUI(this); 
    } 
    catch (Exception e) {} 
    statusBar=new JPanel();
    statusBar.setBackground(Color.LIGHT_GRAY);
    this.getContentPane().add(statusBar,BorderLayout.SOUTH); 
    statusLabel=new JLabel("");
    statusBar.add(statusLabel,BorderLayout.WEST); //状态栏上添加状态标签
    } 
    public void treeCollapsed(TreeExpansionEvent e) {}  //树折叠 

    public void treeExpanded(TreeExpansionEvent e) { //树展开 
    //getLastSelectedPathComponent()返回当前选择的第一个节点中的最后一个路径组件。 
//首选节点的 TreePath 中的最后一个 Object，若未选择任何内容，则返回 null 
        if (tree.getLastSelectedPathComponent()==null) 
            return; 
        if (tree.getLastSelectedPathComponent().toString().trim().equals("我的电脑")) 
            return; 
        TreePath path = e.getPath(); 
        FileNode node = (FileNode)path.getLastPathComponent(); 
        if( ! node.isManager()) { 
        DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); 
        node.Manager(); 
        model.nodeStructureChanged(node); 
      } 
} 


//值变化 
  public void valueChanged(TreeSelectionEvent e) 
  { 
      try{ 
            String s=""; 
            //如果该结点最后一个对象返回值为空，即为底层结点，返回，清空psub 
            if (tree.getLastSelectedPathComponent()==null) 
            return; 
            sfile.removeAll(); 

//如果是本地，则产生目录 
            if (tree.getLastSelectedPathComponent().toString().trim().equals("我的电脑"))
            { 
                File roots[]=File.listRoots(); 
                for(int i=1;i <roots.length;i++) 
                { 
                   String DiskName=roots[i].toString();//电脑上的磁盘名字 
                   DiskName=DiskName.substring(0,DiskName.indexOf(":")+1); 
                   addButton(DiskName,""); 
                } 
            }  
           else
           { 
                Object []path= e.getPath().getPath(); 
                String ss=""; 
                for(int i=1;i <path.length;i++) 
                ss+=File.separator+path[i].toString(); 
                File f = new File(ss.substring(1)); 
                statusLabel.setText(f.toString()); 
                String[] list= f.list(); 
                //定义Vector变量 
                Vector vFile=new Vector(),vDir=new Vector(); 
                for(int i = 0; i < list.length; i++)
                { 
                    if((new File(ss+File.separator+list[i])).isDirectory()) 
                      vDir.addElement(list[i]); 
                    else 
                      vFile.addElement(list[i]); 
                } 
               //排序 
                sortElements(vFile); 
                sortElements(vDir); 

                for(int i=0;i <vDir.size();i++) 
                addButton((String)(vDir.elementAt(i)),ss); 
                for(int i=0;i <vFile.size();i++) 
                addButton((String)(vFile.elementAt(i)),ss); 
         } 
                sfile.doLayout(); 
                sfile.repaint(); 
   }
   catch(Exception ee){} 
 } 


//排序 方法
  public void sortElements(Vector v){ 
      for(int i=0;i <v.size();i++)
      { 
         int k=i; 
         for(int j=i+1;j <v.size();j++) 
         if(((String)(v.elementAt(j))).toLowerCase().compareTo(((String)(v.elementAt(k))).toLowerCase()) <0) 
         k=j; 
         if(k!=i)swap(k,i,v); 
      } 
  } 


//交换 
  private void swap(int loc1,int loc2,Vector v){ 
      Object tmp=v.elementAt(loc1); 
      v.setElementAt(v.elementAt(loc2),loc1); 
      v.setElementAt(tmp,loc2); 
  } 

//添加右侧按钮 
  private void addButton(String fileName,String filePath){ 
      JButton button=new JButton(fileName); 
      button.setBorder(null); 
      button.setHorizontalAlignment(SwingConstants.LEFT); 
      button.setBackground(Color.white); 
      if((new File(filePath+File.separator+fileName)).isDirectory()) 
        button.setIcon(UIManager.getIcon("Tree.closedIcon")); 
      else 
        button.setIcon(UIManager.getIcon("Tree.leafIcon")); 
        sfile.add(button); 
        button.addActionListener(this); 
 } 



  public void actionPerformed(ActionEvent e){ //按钮动作 
  try{ 
      TreePath p=tree.getLeadSelectionPath(); 
      String text=((JButton)(e.getSource())).getText(); 
      Object []path= p.getPath(); 
      String ss=""; 
      for(int i=1;i <path.length;i++) 
      ss+=File.separator+path[i].toString(); 
      ss=ss.substring(1); 
      File f = new File(ss+File.separator+text); 
      statusLabel.setText(f.toString()); 
      if(f.isDirectory())
      { 
         int index=tree.getRowForPath(p); 
         tree.expandRow(index); 
         while(!(tree.getLastSelectedPathComponent().toString().trim().equals(text))) 
         tree.setSelectionRow(index++); 
         tree.expandRow(index-1); 
      } 
      else
     { 
        String postfix=text.toUpperCase(); 
        if(postfix.indexOf(".TXT")!=-1||postfix.indexOf(".JAVA")!=-1|| 
        postfix.indexOf(".HTM")!=-1||postfix.indexOf(".LOG")!=-1) 
        Runtime.getRuntime().exec("NotePad.exe "+ss+File.separator+text);
      //Runtime.getRuntime().exec("NotePad.exe"+ss+text);
        //Runtime.getRuntime().exec("WINWORD.EXE"+ss+File.separator+text);
     } 
    }
  catch(Exception ee){} 
 } 



  private DefaultMutableTreeNode createTreeModel() { //创建树 
      DefaultMutableTreeNode rootNode=new DefaultMutableTreeNode("我的电脑"); 
      File[] rootPath = File.listRoots(); 
      for(int i=1;i <rootPath.length;i++)
      { 
          FileNode Node = new FileNode(rootPath[i]); 
          Node.Manager(); 
          rootNode.add(Node); 
      } 
      return rootNode; 
  } 

  class FileNode extends javax.swing.tree.DefaultMutableTreeNode { //定义一个内部类
    private boolean manager = false; 
    public FileNode(File file)//构造方法
    { 
       setUserObject(file); 
    }  
    public boolean getAllowsChildren()
    { 
        return isDirectory(); 
    }  
    public boolean isLeaf() 
    { 
       return !isDirectory(); 
    } 
    public File getFile()
    { 
       return (File)getUserObject(); 
    } 
    public boolean isManager()
    { 
       return manager; 
    } 
    public boolean isDirectory()
    { 
       return getFile().isDirectory(); 
    }  
    public String toString()
    { 
       File file = (File)getUserObject(); 
       String filename = file.toString(); 
       int index = filename.lastIndexOf(File.separator); 
       return (index != -1 && index != filename.length()-1) ? filename.substring(index+1) : filename; 
    } 
    public void Manager()
    { 
       if(!isDirectory()) return; 
       if(!isManager()) 
       { 
           File file = getFile(); 
           File[] children = file.listFiles(); 
           for(int i=0; i < children.length; ++i) 
           { 
               File f=children[i]; 
               if(f.isDirectory()) 
               add(new FileNode(children[i])); 
           } 
           manager = true; 
      } 
    }
 }
//主方法
 public static void main(String args[]) { 
      new FileManagerJFrame();
 }
} 

